from rest_framework import viewsets, permissions
from rest_framework.response import Response
from rest_framework.exceptions import NotFound
from rest_framework.decorators import action
from rest_framework import status
from django.utils import timezone
from django.shortcuts import get_object_or_404
from .models import Permission, TemporaryPermission
from .serializers import PermissionSerializer, TemporaryPermissionSerializer

class PermissionViewSet(viewsets.ModelViewSet):
    """
    权限管理视图集：包括权限的增、删、改、查操作，添加临时权限和权限更新功能。
    """
    queryset = Permission.objects.all()
    serializer_class = PermissionSerializer
    permission_classes = [permissions.IsAuthenticated]  # 需要认证权限

    def get_queryset(self):
        """
        只返回系统中的权限列表。
        """
        return Permission.objects.all()

    def create(self, request, *args, **kwargs):
        """
        创建新的权限。
        """
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            # 验证通过，创建权限
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def update(self, request, *args, **kwargs):
        """
        修改权限信息。
        """
        permission = self.get_object()  # 获取目标权限
        serializer = self.get_serializer(permission, data=request.data, partial=True)  # 允许部分更新
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def destroy(self, request, *args, **kwargs):
        """
        删除指定权限。
        """
        permission = self.get_object()  # 获取目标权限
        permission.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

    def retrieve(self, request, *args, **kwargs):
        """
        查询指定权限的详细信息。
        """
        permission = self.get_object()  # 获取目标权限
        serializer = self.get_serializer(permission)
        return Response(serializer.data)

    @action(detail=False, methods=['get'], permission_classes=[permissions.IsAuthenticated])
    def permission_list(self, request):
        """
        查询所有权限列表。
        """
        permissions = self.get_queryset()
        serializer = PermissionSerializer(permissions, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['post'], permission_classes=[permissions.IsAuthenticated])
    def assign_temporary_permission(self, request):
        """
        为特定用户分配临时权限。
        """
        user = request.data.get('user')
        permission_level = request.data.get('permission_level')
        knowledge_base = request.data.get('knowledge_base')
        expiration_time = request.data.get('expiration_time')

        # 生成临时权限
        temp_permission = TemporaryPermission.objects.create(
            user=user,
            permission_level=permission_level,
            knowledge_base=knowledge_base,
            expiration_time=expiration_time,
            granted_by=request.user  # 记录审批的管理员
        )
        return Response(TemporaryPermissionSerializer(temp_permission).data, status=status.HTTP_201_CREATED)

    @action(detail=False, methods=['get'], permission_classes=[permissions.IsAuthenticated])
    def check_temp_permissions(self, request):
        """
        查看用户当前的临时权限。
        """
        user = request.user
        temp_permissions = TemporaryPermission.objects.filter(user=user)
        serializer = TemporaryPermissionSerializer(temp_permissions, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['get'], permission_classes=[permissions.IsAuthenticated])
    def auto_update_permissions(self, request):
        """
        自动根据知识库更新角色权限。
        """
        # 这里可以调用模型更新逻辑，更新角色的权限，基于新的知识库变更
        updated_permissions = self.update_role_permissions_based_on_new_knowledge_base()
        return Response(updated_permissions, status=status.HTTP_200_OK)

    def update_role_permissions_based_on_new_knowledge_base(self):
        """
        根据知识库更新角色权限的逻辑。此部分逻辑根据实际情况调整。
        """
        # 获取最新的知识库和角色权限信息，更新角色权限。
        # 假设有一个 `KnowledgeBase` 模型用于管理知识库和其分类
        updated_permissions = []
        knowledge_bases = KnowledgeBase.objects.all()

        for kb in knowledge_bases:
            # 假设每个角色在其权限层级内将自动获取访问权限
            for role in ['高级', '中级', '低级']:
                # 查找相应角色，并根据知识库层级自动调整其权限
                permissions = Permission.objects.filter(role=role, knowledge_base=kb)
                updated_permissions.extend(permissions)

        return updated_permissions
